import { reqcartadd, reqgetgoodsinfo } from "../../http/api";
import qs from "qs";
import { Toast } from "antd-mobile";
//初始值
const initState = {
  info: {},
  newtype: 1,
};

//types
const TYPES = {
  DETAIL_CHANGE_INFO: "DETAIL_CHANGE_INFO",
  DETAIL_CHANGE_NEWTYPE: "DETAIL_CHANGE_NEWTYPE",
};

//修改state的reducer
const reducer = (state = initState, action) => {
  switch (action.type) {
    case TYPES.DETAIL_CHANGE_INFO:
      return {
        ...state,
        info: action.info,
      };
    case TYPES.DETAIL_CHANGE_NEWTYPE:
      return {
        ...state,
        newtype: action.newtype,
      };
    default:
      return state;
  }
};

//actionCreators
export const actions = {
  changeInfo: (info) => ({
    type: TYPES.DETAIL_CHANGE_INFO,
    info,
  }),
  changeType: (newtype) => ({
    type: TYPES.DETAIL_CHANGE_NEWTYPE,
    newtype,
  }),

  //获取信息逻辑
  getDetail: (props) => {
    return (dispatch, getState) => {
      let str = props.location.search.slice(1);
      let result = qs.parse(str);
      let id = Number(result.id);
      if (result.type) {
        dispatch(actions.changeType(result.type))
      }
      //获取信息请求
      reqgetgoodsinfo({id}).then(res=>{
          if(res.data.code==200){
              dispatch(actions.changeInfo(res.data.list[0]))
          }
      })
    };
  },
  //加入购物车
  addShop:()=>{
      return (dispatch,getState)=>{
        let uid = JSON.parse(sessionStorage.getItem("userInfo")).uid;
        let {detail:{info,newtype}} = getState();
        reqcartadd({uid,type:newtype,goodsid:info.id,num:1}).then(res=>{
            if(res.data.code==200){
                Toast.show({
                    icon: "success",
                    content: "添加成功",
                });
            }
        })
      }
  }

};

//导出数据
export const getInfo = (state) => state.detail.info;
export const getNewType = (state) => state.detail.newType;

//导出reducer
export default reducer;
